package com.yun.hibernate.controller;

import com.yun.hibernate.domain.entity.User;
import com.yun.hibernate.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.util.List;

/**
 * @ClassName getInfo
 * @Author lulei
 * @Data 2020/2/24 18:18
 *  */

@RestController
public class UserController {

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ApiOperation(value = "无参")
    public Object getInfo() {

        User user = new User();

        user.setAddress("广州市天河区");
        user.setName("张奇");
        user.setNumber("13698956545");
        return Result.success(user);
    }

    @RequestMapping(value = "/test1",method = RequestMethod.POST)
    @ApiOperation(value = "有参")
    @ApiImplicitParam(paramType = "query",name = "userName",required = true,dataType = "string")
    public Object getInfo1(@RequestParam("userName") String userName) {



        return Result.success(userName);

    }


    /**
     * 有多个参数的玩法
     * @return
     */
    @RequestMapping(value = "test2",method = RequestMethod.GET)
    @ApiOperation(value = "多个参数",notes = "调用当前方法的注意事项")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "userName",value = "用户名",required =true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "password",value = "密码",required =true,dataType = "String")

    })
    public Object getInfo2(@RequestParam("userName") String userName,@RequestParam("password") String password){

        return Result.success(userName + " " + password);
    }

    @RequestMapping(value = "test3",method = RequestMethod.POST)
    @ApiOperation(value = "用户注册，提交对象测试",notes = "json格式")
    public Object register(@RequestBody @Valid User user, BindingResult result) {

        if (result.hasFieldErrors()) {

            String fieldName = null;
            String message = null;
            List<FieldError> fieldErrors = result.getFieldErrors();

            for (FieldError f : fieldErrors) {

                fieldName = f.getField();
                message = f.getDefaultMessage();

            }

             return Result.defineError(fieldName + ":" + message);
        }

        return Result.success("注册成功！");
    }

    @RequestMapping(value = "test4",method = RequestMethod.POST)
    @ApiOperation(value = "提交文件测试")
    public Object getInfo4(@RequestParam("fileUpload")MultipartFile fileUpload) {

       MultipartFile temp = fileUpload;
        return Result.success(null);

    }

}
